package com.hxzy.controller.userinfo;

import com.alibaba.fastjson.JSONObject;
import com.hxzy.common.BaseServlet;
import com.hxzy.common.ResultAjax;
import com.hxzy.util.BeanValidatorUtil;
import com.hxzy.entity.UserInfo;
import com.hxzy.service.UserInfoService;
import com.hxzy.service.impl.UserInfoServiceImpl;
import org.mindrot.jbcrypt.BCrypt;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

/**
 * @Description:
 * @Author: ykj
 * @Date: 2022/3/1 18:08
 */
@WebServlet(urlPatterns = "/web/update")
public class UpdateServlet extends BaseServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        req.setCharacterEncoding("UTF-8");

        //获取数据
        try {
            UserInfo userInfo = super.CollectiongParameterVlues(req, UserInfo.class);
            //验证数据
            Set<String> validator = BeanValidatorUtil.validator(UserInfo.class, userInfo);
            //判断数据是否正确
            if (validator.isEmpty()){
                //正确
                //加密
                String hashpw = BCrypt.hashpw(userInfo.getLoginPwd(), BCrypt.gensalt());
                userInfo.setLoginPwd(hashpw);
                //调用修改操作
                UserInfoService userInfoService=new UserInfoServiceImpl();
                int update = userInfoService.update(userInfo);
                //获取返回的信息
                ResultAjax resultAjax=null;
                if (update>0){
                    resultAjax = ResultAjax.success("更新成功");
                }else {
                    resultAjax = ResultAjax.error("更新失败");
                }
                //向页面传递输出信息
                super.render(resp, JSONObject.toJSONString(resultAjax));
            }else {
                //迭代失败信息
                String next = validator.iterator().next();
                ResultAjax error = ResultAjax.error(next);
                super.render(resp, JSONObject.toJSONString(error));
            }

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
